package algorithms;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import dataStructure.HashTreeNode;
import dataStructure.INode;
import dataStructure.ItemSet;

public class StraightForwardAlgo extends Algo {

	public HashMap<String, Integer> histogram;

	public StraightForwardAlgo(String pathFormat, int startIndex, int endIndex) {
		super(pathFormat, startIndex, endIndex);
		histogram = new HashMap<String, Integer>();
	}

	public List<String> findFrequentItemSet(double support, int maxK) {

		BufferedReader br;
		FileReader fr;
		String line;
		String[] tmpBasket;
		LinkedList<String> result = new LinkedList<String>();

		iterNum++;

		numOfItems = 0;
		numOfBaskets = 0;
		for (int i = fileStartIndex; i <= fileEndIndex; i++) {
			try {
				fr = new FileReader(String.format(filePathFormat, i));
				br = new BufferedReader(fr);
				while ((line = br.readLine()) != null) {
					if (line.startsWith("#") || line.equals(""))
						// Ignore comments
						continue;
					else {
						line = line.toLowerCase();
						tmpBasket = line.split(",");
						numOfItems += tmpBasket.length;
						numOfBaskets++;
						newBasket(tmpBasket, maxK);
					}
				}
				br.close();
				fr.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		for (String string : histogram.keySet()) {
			int val = histogram.get(string);
			if (val > support * numOfBaskets)
				result.add(string);
		}
		
		return result;
	}

	protected void newBasket(String[] tmpBasket, int maxK) {
		Arrays.sort(tmpBasket);
		String subsetStr;

		List<List<String>> subsets = Common.getAllSubsets(tmpBasket, 1);

		for (int i = 2; i <= maxK; i++) {
			List<List<String>> tmp = Common.getAllSubsets(tmpBasket, i);
			if (tmp == null)
				break;
			subsets.addAll(tmp);
		}
		if (subsets == null)
			return;
		for (List<String> list : subsets) {
			subsetStr = list.toString();
			if (histogram.containsKey(subsetStr))
				histogram.put(subsetStr, histogram.get(subsetStr) + 1);
			else
				histogram.put(subsetStr, 1);
		}
	}

	@Override
	public INode findFrequentItemSet(double support, int minimumK, int maxK) {
		// TODO Auto-generated method stub
		return null;
	}
}
